﻿#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct PersonNestPointer
{
	char* name;
	int age;
};
//1.分配内存；
struct PersonNestPointer** allocatePointerSpace()
{
	//2.结构体二级指针temp，指向三个一级指针开辟的内存；
	struct PersonNestPointer** temp = malloc(sizeof(struct PersonNestPointer*) * 3);
	for (int i = 0; i < 3; ++i)
	{
		//3.temp[i]就是结构体一级指针struct PersonNestPointer*，指向具体的结构体struct PersonNestPointer；
		temp[i] = malloc(sizeof(struct PersonNestPointer));
		//4.temp[i]是结构体指针变量，获取char*变量name，再为name开辟堆内存；
		temp[i]->name = malloc(sizeof(char) * 64);

		sprintf(temp[i]->name, "Name_%d", i + 1);
		temp[i]->age = 100 + i;
	}
	return temp;
};
//5.打印输出内容；
void printPersonNest(struct PersonNestPointer** person)
{
	if (NULL == person)
	{
		return;
	}
	for (int i = 0; i < 3; ++i)
	{
		printf("6.输出结构体指针person[i]的name和age：%s  %d\n", person[i]->name, person[i]->age);
	}
}
//7.释放内存，char*内存，struct PersonNestPointer内存，struct PersonNestPointer*内存；
void freePersonNestSpace(struct PersonNestPointer** person)
{
	if (NULL == person)
	{
		return;
	}
	for (int i = 0; i < 3; ++i)
	{
		if (person[i] == NULL)
		{
			continue;
		}
		if (person[i]->name != NULL)
		{
			printf("8.此时结构体指针person[i]的name：%s的内存被释放！\n", person[i]->name);//Name_1，Name_2，Name_3
			free(person[i]->name);
			person[i]->name = NULL;
		}
		free(person[i]);
		person[i] = NULL;
	}
	free(person);
	person = NULL;
}
void testConstructNest()
{
	struct PersonNestPointer** person = NULL;
	person = allocatePointerSpace();
	printPersonNest(person);//Name_1  100，Name_2  101，Name_3  102
	freePersonNestSpace(person);
}

//main207：结构体嵌套一级指针
int main207()
{
	testConstructNest();

	system("pause");
	return EXIT_SUCCESS;
}